package com.fanxj.Utils;
import org.mozilla.universalchardet.UniversalDetector;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
public class CharsetDetectorUtils {
    /**
     * 检测文件流的编码格式
     * @param inputStream 文件输入流
     * @return 编码名称（如 UTF-8、GBK），若检测失败返回 null
     */
    public static String detectEncoding(InputStream inputStream) throws IOException {
        UniversalDetector detector = new UniversalDetector(null);
        byte[] buf = new byte[4096];
        int nread;
        while ((nread = inputStream.read(buf)) > 0 && !detector.isDone()) {
            detector.handleData(buf, 0, nread);
        }
        detector.dataEnd();
        String encoding = detector.getDetectedCharset();
        detector.reset();
        inputStream.reset(); // 重置流以便后续读取
        return encoding;
    }
    /**
     * 检查输入流中的数据是否可能是 UTF-8 编码
     * @param inputStream 文件输入流
     * @return true 表示可能是 UTF-8，false 表示不可能是 UTF-8
     */
    public static boolean isLikelyUTF8(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[4096];
        int bytesRead = inputStream.read(buffer);
        if (bytesRead == -1) {
            return false; // 空文件
        }

        CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder()
                .onMalformedInput(CodingErrorAction.REPORT)  // 遇到非法字符时报错
                .onUnmappableCharacter(CodingErrorAction.REPORT);

        try {
            decoder.decode(ByteBuffer.wrap(buffer, 0, bytesRead));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}